<?php
/**
 * @version $Id: xmlelement.php 1212 2010-05-26 20:13:35Z elkuku $
 * @package    EasyCreator
 * @subpackage Helpers
 * @author     EasyJoomla {@link http://www.easy-joomla.org Easy-Joomla.org}
 * @author     Nikolai Plath (elkuku) {@link http://www.nik-it.de NiK-IT.de}
 * @author     Created on 29-Feb-2008
 * @license    GNU/GPL, see JROOT/LICENSE.php
 */

// No direct access
defined('JPATH_BASE') or die;

/**
 * Wrapper class for php SimpleXMLElement.
 *
 * @package		Joomla.Framework
 * @subpackage  Utilities
 * @since		1.6
 */
class EasyXMLElement extends SimpleXMLElement
{
    /**
     * Return a well-formed XML string based on SimpleXML element
     *
     * @param	boolean	Should we use indentation and newlines ?
     * @param	integer	Indentaion level.
     * @return	string
     */
    public function asFormattedXML($compressed = false, $indent = '  ', $level = 0)
    {
        $out = '';

        // Start a new line, indent by the number indicated in $level
        $out .= ($compressed) ? '' : "\n".str_repeat($indent, $level);

        // Add a <, and add the name of the tag
        $out .= '<'.$this->getName();

        // For each attribute, add attr="value"
        foreach($this->attributes() as $attr)
        {
            $out .= ' '.$attr->getName().'="'.htmlspecialchars((string)$attr, ENT_COMPAT, 'UTF-8').'"';
        }

        // If there are no children and it contains no data, end it off with a />
        if( ! count($this->children())
        && ! (string)$this)
        {
            $out .= " />";
        }
        else
        {
            // If there are children
            if(count($this->children()))
            {
                // Close off the start tag
                $out .= '>';

                $level ++;

                // For each child, call the asFormattedXML function (this will ensure that all children are added recursively)
                foreach ($this->children() as $child)
                {
                    $out .= $child->asFormattedXML($compressed, $indent, $level);
                }//foreach

                $level --;

                // Add the newline and indentation to go along with the close tag
                $out .=($compressed) ? '' : "\n".str_repeat($indent, $level);
            }
            elseif((string)$this)
            {
                // If there is data, close off the start tag and add the data
                $out .= '>'.htmlspecialchars((string)$this, ENT_COMPAT, 'UTF-8');
            }

            // Add the end tag
            $out .= '</'.$this->getName().'>';
        }

        return $out;
    }//function

}//class
